<template>
  <div class="tree-main-body">
    <!-- 左侧分类树 -->
    <div class="left-box">
      <TreeCategory
        :selected="categoryIds"
        type="no-cate"
        text="课件"
        @update="handleCategoryUpdate"
      />
    </div>

    <!-- 右侧操作区 -->
    <div class="right-box">
      <div class="d-flex playedu-main-title float-left mb-24">
        课件 | {{ selLabel }}
      </div>

      <!-- 操作按钮和搜索 -->
      <div class="float-left j-b-flex mb-24">
        <div class="d-flex">
          <UploadCoursewareButton
            :categoryIds="categoryIds"
            @update="resetList"
          />
          <a-button class="ml-16" @click="multiConfig = !multiConfig">
            {{ multiConfig ? "取消操作" : "批量操作" }}
          </a-button>
          <a-button
            class="ml-16"
            :disabled="selectedRowKeys.length === 0"
            @click="removeResourceMulti"
          >
            删除
          </a-button>
        </div>
        <div class="d-flex">
          <div class="d-flex mr-24">
            <a-typography-text>名称：</a-typography-text>
            <a-input
              v-model:value="title"
              allowClear
              style="width: 160px"
              placeholder="请输入名称关键字"
            />
          </div>
          <div class="d-flex mr-24">
            <a-typography-text>格式：</a-typography-text>
            <a-select
              style="width: 160px"
              v-model:value="type"
              :options="types"
              placeholder="请选择格式"
            />
          </div>
          <a-button class="mr-16" @click="resetList">重置</a-button>
          <a-button type="primary" @click="refreshPage">查询</a-button>
        </div>
      </div>

      <!-- 课件表格 -->
      <a-table
        v-if="multiConfig"
        :row-selection="{ type: 'checkbox', ...rowSelection }"
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="paginationProps"
        row-key="id"
      />
      <a-table
        v-else
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="paginationProps"
        row-key="id"
      />

      <!-- 编辑弹窗 -->
      <CoursewareUpdateDialog
        :id="updateId"
        v-model:open="updateVisible"
        @onSuccess="handleUpdateSuccess"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, h } from "vue";
import { useRoute } from "vue-router";
import { Modal, message, Space, Button } from "ant-design-vue";
import { ExclamationCircleFilled } from "@ant-design/icons-vue";
import { resource } from "@/api";
import { dateFormat } from "@/utils";
import TreeCategory from '@/components/Common/tree-category.vue'
import UploadCoursewareButton from '@/components/Common/upload-courseware-button.vue'
import CoursewareUpdateDialog from "./upload-dialog.vue";

interface DataType {
  admin_id: number;
  created_at: string;
  disk: string;
  extension: string;
  file_id: string;
  id: number;
  name: string;
  parent_id: number;
  path: string;
  size: number;
  type: string;
  url: string;
}

const route = useRoute();

// 状态
const list = ref<DataType[]>([]);
const adminUsers = ref<Record<number, string>>({});
const existingTypes = ref<string[]>([]);
const resourceUrl = ref<Record<number, string>>({});
const refresh = ref(false);
const page = ref(1);
const size = ref(10);
const total = ref(0);
const loading = ref(true);
const categoryIds = ref<number[]>([]);
const selectedRowKeys = ref<number[]>([]);
const type = ref("WORD,EXCEL,PPT,PDF,TXT,RAR,ZIP");
const title = ref("");
const multiConfig = ref(false);
const selLabel = ref(route.query.label ? String(route.query.label) : "全部课件");
const cateId = ref(Number(route.query.cid) || 0);
const updateId = ref(0);
const updateVisible = ref(false);

// 格式选项
const types = [
  { label: "全部", value: "WORD,EXCEL,PPT,PDF,TXT,RAR,ZIP" },
  { label: "WORD", value: "WORD" },
  { label: "EXCEL", value: "EXCEL" },
  { label: "PPT", value: "PPT" },
  { label: "PDF", value: "PDF" },
  { label: "TXT", value: "TXT" },
  { label: "RAR", value: "RAR" },
  { label: "ZIP", value: "ZIP" },
];

// 获取课件列表
const getList = () => {
  loading.value = true;
  const categoryStr = categoryIds.value.join(",");
  console.log('----------title', title.value)
  console.log('----------type', type.value)
  resource
    .resourceList(page.value, size.value, "", "", title.value, type.value, categoryStr)
    .then((res: any) => {
      total.value = res.data.result.total;
      list.value = res.data.result.data;
      existingTypes.value = res.data.existing_types;
      adminUsers.value = res.data.admin_users;
      resourceUrl.value = res.data.resource_url;
      loading.value = false;
    })
    .catch((err) => {
      console.log(err);
      loading.value = false;
    });
};

// 分页
const paginationProps = reactive({
  get current() { return page.value },
  get pageSize() { return size.value },
  get total() { return total.value },
  showSizeChanger: true,
  onChange: (p: number, s: number) => {
    page.value = p;
    size.value = s;
  },
});

// 监听刷新或分页
watch([categoryIds, page, size, refresh], getList, { immediate: true });

// 表格列
const columns = [
  {
    title: "课件名称",
    key: "name",
    customRender: ({ record }: any) => {
      return h("div", { class: "d-flex" }, [
        h("i", {
          class: "iconfont icon-icon-file",
          style: "font-size:16px;color:rgba(0,0,0,0.3)",
        }),
        h("span", { class: "ml-8" }, `${record.name}.${record.extension}`),
      ]);
    },
  },
  {
    title: "课件格式",
    dataIndex: "type",
    key: "type",
  },
  {
    title: "课件大小",
    dataIndex: "size",
    key: "size",
    customRender: ({ text }: any) => h("span", {}, (text / 1024 / 1024).toFixed(2) + "M"),
  },
  {
    title: "创建人",
    dataIndex: "admin_id",
    key: "admin_id",
    customRender: ({ text }: any) => h("span", {}, adminUsers.value[text] || ""),
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    key: "created_at",
    customRender: ({ text }: any) => h("span", {}, dateFormat(text)),
  },
  {
    title: "操作",
    key: "action",
    fixed: "right",
    width: 180,
    customRender: ({ record }: any) =>
      h(Space, { size: "small" }, [
        h(
          Button,
          { type: "link", onClick: () => downloadFile(record) },
          () => "下载"
        ),
        h(
          Button,
          {
            type: "link",
            onClick: () => {
              updateId.value = record.id;
              updateVisible.value = true;
            },
          },
          () => "编辑"
        ),
        h(
          Button,
          { type: "link", onClick: () => removeResource(record.id) },
          () => "删除"
        ),
      ]),
  },
];

// 行选择
const rowSelection = {
  onChange: (keys: number[]) => (selectedRowKeys.value = keys),
};

// 重置列表
const resetList = () => {
  page.value = 1;
  size.value = 10;
  list.value = [];
  title.value = "";
  selectedRowKeys.value = [];
  type.value = "WORD,EXCEL,PPT,PDF,TXT,RAR,ZIP";
  refresh.value = !refresh.value;
};

// 删除单个
const removeResource = (id: number) => {
  if (!id) return;
  Modal.confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "删除前请检查选中课件文件无关联课程，确认删除？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk() {
      resource.destroyResource(id).then(() => {
        message.success("删除成功");
        resetList();
      });
    },
  });
};

// 批量删除
const removeResourceMulti = () => {
  if (!selectedRowKeys.value.length) return;
  Modal.confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "删除前请检查选中课件文件无关联课程，确认删除？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    onOk() {
      resource.destroyResourceMulti(selectedRowKeys.value).then(() => {
        message.success("删除成功");
        resetList();
      });
    },
  });
};

// 下载
const downloadFile = (record: DataType) => {
  const url = resourceUrl.value[record.id];
  const a = document.createElement("a");
  a.href = url;
  a.download = `${record.name}.${record.extension}`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

// 分类树更新
const handleCategoryUpdate = (keys: number[], title: any) => {
  page.value = 1;
  categoryIds.value = keys;
  selLabel.value = typeof title === "string" ? title : title.props.children[0];
};

// 查询刷新
const refreshPage = () => {
  page.value = 1;
  refresh.value = !refresh.value;
};

// 编辑弹窗回调
const handleUpdateSuccess = () => {
  updateVisible.value = false;
  refresh.value = !refresh.value;
};

</script>

<style scoped>

</style>
